/**
 * 动画相关的组合式函数
 * 提供动画控制、状态管理等功能
 */

import { ref, computed, onBeforeUnmount } from 'vue'
import { AnimationController, AnimationState } from '../core/animation'

// 动画控制组合式函数
export function useAnimationController(duration = 5) {
  const controller = new AnimationController(duration)
  const state = ref(controller.getState())

  // 更新状态的函数
  const updateState = () => {
    state.value = controller.getState()
  }

  // 监听控制器事件
  controller.on('timeUpdate', updateState)
  controller.on('stateChange', updateState)

  // 计算属性
  const isPlaying = computed(() => state.value.state === AnimationState.PLAYING)
  const isPaused = computed(() => state.value.state === AnimationState.PAUSED)
  const isStopped = computed(() => state.value.state === AnimationState.STOPPED)
  const currentTime = computed(() => state.value.currentTime)
  const totalDuration = computed(() => state.value.totalDuration)
  const progress = computed(() => 
    totalDuration.value > 0 ? currentTime.value / totalDuration.value : 0
  )

  // 控制方法
  const play = () => controller.play()
  const pause = () => controller.pause()
  const stop = () => controller.stop()
  const seekTo = (time: number) => controller.seekTo(time)
  const setConfig = (config: any) => controller.setConfig(config)

  // 清理
  onBeforeUnmount(() => {
    controller.dispose()
  })

  return {
    // 状态
    state: state.value,
    isPlaying,
    isPaused,
    isStopped,
    currentTime,
    totalDuration,
    progress,

    // 方法
    play,
    pause,
    stop,
    seekTo,
    setConfig,

    // 原始控制器（用于高级操作）
    controller
  }
}

// 关键帧动画组合式函数
export function useKeyframeAnimation() {
  const keyframes = ref<any[]>([])
  const currentKeyframe = ref<any | null>(null)

  const addKeyframe = (keyframe: any) => {
    keyframes.value.push(keyframe)
    keyframes.value.sort((a, b) => a.time - b.time)
  }

  const removeKeyframe = (id: string) => {
    const index = keyframes.value.findIndex(kf => kf.id === id)
    if (index > -1) {
      keyframes.value.splice(index, 1)
    }
  }

  const updateKeyframe = (id: string, updates: any) => {
    const keyframe = keyframes.value.find(kf => kf.id === id)
    if (keyframe) {
      Object.assign(keyframe, updates)
      keyframes.value.sort((a, b) => a.time - b.time)
    }
  }

  const getKeyframeAtTime = (time: number) => {
    return keyframes.value.find(kf => Math.abs(kf.time - time) < 0.01)
  }

  const getKeyframesInRange = (startTime: number, endTime: number) => {
    return keyframes.value.filter(kf => kf.time >= startTime && kf.time <= endTime)
  }

  return {
    keyframes,
    currentKeyframe,
    addKeyframe,
    removeKeyframe,
    updateKeyframe,
    getKeyframeAtTime,
    getKeyframesInRange
  }
}

// 缓动函数组合式函数
export function useEasing() {
  const easingTypes = [
    'linear',
    'ease-in',
    'ease-out',
    'ease-in-out',
    'ease-in-cubic',
    'ease-out-cubic',
    'ease-in-out-cubic',
    'ease-in-quart',
    'ease-out-quart',
    'ease-in-out-quart',
    'ease-in-back',
    'ease-out-back',
    'bounce'
  ]

  const getEasingFunction = (type: string) => {
    // 从动画引擎获取缓动函数
    return import('../core/engine/animation').then(m => m.easingFunctions[type])
  }

  const previewEasing = (type: string, duration = 1000) => {
    return new Promise<void>((resolve) => {
      const startTime = performance.now()
      
      const animate = (currentTime: number) => {
        const elapsed = currentTime - startTime
        const progress = Math.min(elapsed / duration, 1)
        
        getEasingFunction(type).then(easingFn => {
          const easedProgress = easingFn(progress)
          
          // 触发预览回调
          if (progress < 1) {
            requestAnimationFrame(animate)
          } else {
            resolve()
          }
        })
      }
      
      requestAnimationFrame(animate)
    })
  }

  return {
    easingTypes,
    getEasingFunction,
    previewEasing
  }
}

// 性能监控组合式函数
export function useAnimationPerformance() {
  const stats = ref({
    fps: 0,
    frameTime: 0,
    memoryUsage: 0,
    activeAnimations: 0
  })

  const startMonitoring = () => {
    let frameCount = 0
    let lastTime = performance.now()
    
    const monitor = () => {
      const currentTime = performance.now()
      frameCount++
      
      if (currentTime - lastTime >= 1000) {
        stats.value.fps = frameCount
        frameCount = 0
        lastTime = currentTime
        
        // 更新内存使用情况
        if ('memory' in performance) {
          stats.value.memoryUsage = (performance as any).memory.usedJSHeapSize / 1024 / 1024
        }
      }
      
      requestAnimationFrame(monitor)
    }
    
    requestAnimationFrame(monitor)
  }

  const updateStats = (newStats: Partial<typeof stats.value>) => {
    Object.assign(stats.value, newStats)
  }

  return {
    stats,
    startMonitoring,
    updateStats
  }
}
